import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    // 侧边栏
    sidebar: {
      opened: true,
      withoutAnimation: false
    },
    // 设备类型
    device: 'desktop',
    // 主题
    theme: 'light',
    // 语言
    language: 'zh-cn',
    // 页面加载状态
    loading: false,
    // 面包屑
    breadcrumbs: [],
    // 标签页
    visitedViews: [],
    cachedViews: []
  }),

  getters: {
    sidebarOpened: (state) => state.sidebar.opened,
    isMobile: (state) => state.device === 'mobile'
  },

  actions: {
    // 切换侧边栏
    toggleSidebar() {
      this.sidebar.opened = !this.sidebar.opened
      this.sidebar.withoutAnimation = false
    },

    // 关闭侧边栏
    closeSidebar(withoutAnimation) {
      this.sidebar.opened = false
      this.sidebar.withoutAnimation = withoutAnimation
    },

    // 设置设备类型
    toggleDevice(device) {
      this.device = device
    },

    // 设置主题
    setTheme(theme) {
      this.theme = theme
      document.documentElement.setAttribute('data-theme', theme)
    },

    // 设置语言
    setLanguage(language) {
      this.language = language
    },

    // 设置加载状态
    setLoading(loading) {
      this.loading = loading
    },

    // 设置面包屑
    setBreadcrumbs(breadcrumbs) {
      this.breadcrumbs = breadcrumbs
    },

    // 添加访问的视图
    addVisitedView(view) {
      if (this.visitedViews.some(v => v.path === view.path)) return
      this.visitedViews.push({
        name: view.name,
        path: view.path,
        title: view.meta?.title || 'no-name'
      })
    },

    // 添加缓存的视图
    addCachedView(view) {
      if (this.cachedViews.includes(view.name)) return
      if (view.meta?.keepAlive) {
        this.cachedViews.push(view.name)
      }
    },

    // 删除访问的视图
    delVisitedView(view) {
      const index = this.visitedViews.findIndex(v => v.path === view.path)
      if (index > -1) {
        this.visitedViews.splice(index, 1)
      }
    },

    // 删除缓存的视图
    delCachedView(view) {
      const index = this.cachedViews.indexOf(view.name)
      if (index > -1) {
        this.cachedViews.splice(index, 1)
      }
    },

    // 删除其他访问的视图
    delOthersVisitedViews(view) {
      this.visitedViews = this.visitedViews.filter(v => v.path === view.path)
    },

    // 删除所有访问的视图
    delAllVisitedViews() {
      this.visitedViews = []
    },

    // 删除所有缓存的视图
    delAllCachedViews() {
      this.cachedViews = []
    }
  }
})
